package com.cy.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class EasyExcelDemo {


	public static void main(String[] args) {
		String directoryPath = "D:/LSLS/data";
		String outputFilePath = "D:/LSLS/cykankan.xlsx";

		List<ExcelData> aggregatedData = new ArrayList<>();

		File dir = new File(directoryPath);
		File[] files = dir.listFiles((d, name) -> name.endsWith(".xlsx"));

		if (files != null) {
			for (File file : files) {
				ExcelReaderBuilder readerBuilder = EasyExcel.read(file, ExcelData.class, new AnalysisEventListener<ExcelData>() {
					@Override
					public void invoke(ExcelData excelData, AnalysisContext context) {
						excelData.setFileName(file.getName());
						aggregatedData.add(excelData);
					}

					@Override
					public void doAfterAllAnalysed(AnalysisContext context) {
						// 文件读取完成后的操作
					}
				});

				// 跳过第一行标题行
				ExcelReaderSheetBuilder sheetBuilder = readerBuilder.sheet().headRowNumber(1);
				sheetBuilder.doRead();
			}

			// 将汇总的数据写入新的 Excel 文件
			ExcelWriterBuilder writerBuilder = EasyExcel.write(outputFilePath, ExcelData.class);
			ExcelWriterSheetBuilder writerSheetBuilder = writerBuilder.sheet("Sheet1");
			writerSheetBuilder.doWrite(aggregatedData);
		}
	}
}
